
import store from '../store'
import messageType from "@/utils/message-type";
import { Notification } from 'element-ui';
import tim from "@/tim";


// webSocket与服务端连接的地址
// const wsUrl = 'ws://localhost:8090/element_admin/chat/'
// const wssUrl = 'wss://localhost:8090/element_admin/chat/'
const wsUrl = 'ws://www.hrkj.fit:8090/ljb_16/element_admin/chat/'
const wssUrl = 'wss://www.hrkj.fit:8090/ljb_16/element_admin/chat/'

// 重连状态
let lockReconnect = false;

// 关闭重连
let closeReconnect;


let socket;

export function initialSocket(){
     closeReconnect = false
    if("WebSocket" in window){
      console.log("webSocket连接地址："+wsUrl)
      if(window.location.protocol === "http:"){
        socket = new WebSocket(wsUrl+store.getters.id)
      }else {
        socket = new WebSocket(wssUrl+store.getters.id)
      }
      socket.onopen = onOpen
      socket.onclose = onClose
      socket.onerror = onError
      socket.onmessage = onMessage
    }else{
      console.log("该浏览器暂不支持WebSocket")
    }
}



/**
 * 关闭webSocket 连接
 */
export function closeSocket() {
  closeReconnect = true // 关闭重连
  socket.close() // 关闭webSocket
}


const onOpen = ()=> {
  console.log("与服务端建立webSocket连接成功！")
}

const onClose = ()=>{
  console.log("关闭与服务端的webSocket连接")
  if(!closeReconnect){
    reconnect()
  }

}

const onError = err=>{
  console.log("webSocket连接出现错误：")
  console.log(err)
  if(!closeReconnect){
    reconnect()
  }
}

// 重连
function reconnect() {
  if(lockReconnect) return
  lockReconnect = true
  setTimeout(function () {
    initialSocket()
    lockReconnect = false
  },2000)
}

const onMessage = res =>{
  console.log("webSocket服务端发送来消息："+res)
  let message = JSON.parse(res.data)
  switch (message.type) {
    case messageType.REFRESH_REQ_MESSAGE: // 刷新请求添加好友消息列表
      store.dispatch('chat/getRequestMessageList').then(()=>{
        if(message.content){
          Notification.info({title: "系统通知",
            dangerouslyUseHTMLString: true,
            message: message.content});
        }
      })
      break;
    case messageType.REFRESH_FRIEND_LIST: // 刷新好友列表
      store.dispatch('chat/getFriendList').then(()=>{
        if(message.content){
          Notification.info({
            title:"系统通知",
            dangerouslyUseHTMLString: true,
            message:message.content})
        }
      })
      break
    case messageType.SYSTEM_NOTICE_MESSAGE: // 通知消息
      if(message.content){
        Notification.success({
          title:'系统通知',
          dangerouslyUseHTMLString:true,// 内容支持html
          message: message.content
        })
      }
      break
    case messageType.DELETE_CONVERSATION: // 删除指定会话
      console.log("将要删除会话id："+message.senderId)
      tim.deleteConversation('C2C' + message.senderId).then((res) => {
        console.log("删除会话id：" + res.data)
      });
      break;
  }
  console.log(message)
}

/**
 * 使用webSocket发送消息
 * @param message 消息
 */
export function sendMessage(message) {
  socket.send(JSON.stringify(message))
}
